package com.suyundeng.warehousemanage.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.suyundeng.entity.*;
import com.suyundeng.warehousemanage.service.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.suyundeng.entity.JsonResult;
import com.suyundeng.entity.MyProduct;
import com.suyundeng.entity.TCargoArea;
import com.suyundeng.entity.TWare;
import com.suyundeng.warehousemanage.service.ITCargoAreaService;
import com.suyundeng.warehousemanage.service.ITWareService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.Array;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xh
 * @since 2021-04-19
 */
@RestController
public class TWareController {

    @Autowired
    private ITWareService itWareService;

    @Autowired
    private ITCargoService itCargoService;

    @Autowired
    private ITIoWarehouseService ioWarehouseService;

    @Autowired
    private ITIomWarehouseService iomWarehouseService;

    @Autowired
    private ITMoveWarehouseService itMoveWarehouseService;

    @Autowired
    private ITCargoAreaService itCargoAreaService;

    @RequestMapping("/list/t-ware-paging")
    public JsonResult selectAllPaging(@RequestParam(value = "current", required = false, defaultValue = "1") Integer current) {  //分页查询仓库表
        IPage<TWare> page = new Page<>(current, 5);
        IPage<TWare> WareData = itWareService.pagingSelectAllWare(page);
        return new JsonResult(1, "ok", WareData);
    }

    @RequestMapping("/list/t-ware")
    public JsonResult selectAllWare(){//查询所有的仓库name
        List<TWare> list = itWareService.list();
        return new JsonResult(1,"ok",list);
    }

    @RequestMapping("/ware")
    public JsonResult findAllWare(){

        List<TWare> tWares = itWareService.findAllTWare();
        return new JsonResult(1,"ok",tWares);
    }


    @RequestMapping("/proDetails/{outwareName}/{mvGoods}")
    public JsonResult deleteRoleFun(@PathVariable String outwareName, @PathVariable String mvGoods){
        List<MyProduct> myProducts = itWareService.selectMyProduct(mvGoods, outwareName);

        return new JsonResult(1,myProducts);

    }
//    @RequestMapping("/showgoodName/{ware}")
//    public JsonResult selectAllWare(@PathVariable String ware){//查询所有的仓库name
//
//        List<String> list = itWareService.selectgoodName(ware);
//
//        return new JsonResult(1,"ok",list);
//    }


    @RequestMapping("/t-goodnameAll/{ware}")
    public JsonResult selectAllGoodName(@PathVariable String ware){//查询所有的库区name
        List<String> list = itWareService.selectgoodName(ware);
        return new JsonResult(1,"ok",list);
    }

    @PutMapping("/t-ware/updateWare")
    public JsonResult updateWare(@RequestBody TWare tWare){//修改数据
        itWareService.updateById(tWare);
        return new JsonResult(1,"ok",tWare);
    }

    @RequestMapping("/t-ware/select/{warehouseId}&{settledDate}")
    public JsonResult tjSelect(@PathVariable("warehouseId") String id, @PathVariable("settledDate") String settledDate) {//条件查询数据
        if (settledDate.length() == 0 || settledDate.length() == 4) {
            settledDate = "20";
        }
        List<TWare> tWares = itWareService.selectByIdByDate(id, settledDate); //两个条件
        return new JsonResult(1, "ok", tWares);
    }

    @PutMapping("/t-ware/status")
    public JsonResult updateStatus(@RequestBody TWare tWare) { //修改状态
        if (tWare.getStatus().equals("0")) {
            tWare.setStatus("1");
        } else {
            tWare.setStatus("0");
        }
        itWareService.updateById(tWare);
        return new JsonResult(1, "ok", tWare);
    }

    @PostMapping("/addToWare")
    public JsonResult addToWare(@RequestBody TWare tWare) {//添加仓库功能实现
        tWare.setId(UUID.randomUUID().toString().replace("-", "").substring(10));
        LocalDateTime now = LocalDateTime.now();//获取当前时间
        tWare.setDeteTime(Date.from(now.atZone(ZoneId.systemDefault()).toInstant()));
        tWare.setStatus("0");//设置状态
        itWareService.save(tWare); //使用系统方法添加数据
        return new JsonResult(1, "ok", tWare);
    }

    /*根据仓库id查询当前仓库下的所有的库区*/
    @RequestMapping("/t-ware/cargo/{wareId}")
    public JsonResult findAllCargoByWareId(@PathVariable("wareId") String wareId) {

        List<TCargoArea> cargoAresByWareId = itCargoAreaService.findCargoAresByWareId(wareId);
        return new JsonResult(1, "ok", cargoAresByWareId);
    }
//    SELECT ts.* FROM t_shelves ts
//    JOIN t_ware tw ON tw.`id`=ts.`ware_id`
//    WHERE tw.`ware_name`='和田仓'

//    SELECT tca.* FROM t_cargo_area tca
//    JOIN t_shelves ts ON ts.`id`=tca.goods_no
//    WHERE ts.`shelves_no`='10101'

    @RequestMapping("/t-shelvesNo/{goodName}")
    public JsonResult selectShelvesName(@PathVariable String goodName){//查询所有的库区name
        System.out.println(goodName+"+++++++++++++++++++++++++++++++++++++++++++++++++++++++++");

        List<TShelves> list = itWareService.selectShelvesName(goodName);

        return new JsonResult(1,"ok",list);
    }

    @RequestMapping("/t-Tca/{shelvesNo}")
    public JsonResult selectTCAName(@PathVariable String shelvesNo){//查询所有的库区name
        System.out.println(shelvesNo+"+++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
        List<TCargo> list = itWareService.selectTCAName(shelvesNo);

        return new JsonResult(1,"ok",list);
    }

    @PostMapping("/moveware")
    public JsonResult MoveWare(@RequestBody Object admin) throws ParseException {

        HashMap a = (HashMap) admin;
        ArrayList proDetails = (ArrayList) a.get("proDetails");
        ArrayList proDetails2 = (ArrayList) a.get("proDetails2");
        LinkedHashMap adm = (LinkedHashMap) a.get("admin");

        List<MyProduct> myProducts = JSON.parseArray(JSON.toJSONString(proDetails), MyProduct.class);
        List<MyProduct> myProducts2 = JSON.parseArray(JSON.toJSONString(proDetails2), MyProduct.class);

        String ad = (String) adm.get("mvTime");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
        Date dateTrans = format.parse(ad);

        String id = UUID.randomUUID().toString().substring(0, 10);
        String io_no = UUID.randomUUID().toString().substring(0, 10);
        TIoWarehouse tIoWarehouse = new TIoWarehouse();
        tIoWarehouse.setId(id);
        tIoWarehouse.setIoNo(io_no);
        tIoWarehouse.setIoType("调拨出库");
        tIoWarehouse.setBatch(3);
        tIoWarehouse.setPName(myProducts.get(0).getPName());
        tIoWarehouse.setPBrand(myProducts.get(0).getPName());
        String mvNumber = (String) adm.get("mvNumber");
        tIoWarehouse.setPNum(Integer.valueOf(mvNumber));
        tIoWarehouse.setWName(myProducts.get(0).getWareName());

        tIoWarehouse.setIoTime(dateTrans);
        tIoWarehouse.setCompanyId("2");
        ioWarehouseService.save(tIoWarehouse);

        TIoWarehouse tIoWarehouse2 = new TIoWarehouse();
        String id2 = UUID.randomUUID().toString().substring(0, 11);

        tIoWarehouse2.setId(id2);
        tIoWarehouse2.setIoNo(io_no);
        tIoWarehouse2.setIoType("调拨入库");
        tIoWarehouse2.setBatch(3);
        tIoWarehouse2.setPName(myProducts.get(0).getPName());
        tIoWarehouse2.setPBrand(myProducts.get(0).getPName());
        tIoWarehouse2.setPNum(Integer.valueOf(mvNumber));
        tIoWarehouse2.setWName(myProducts2.get(0).getWareName());
        tIoWarehouse2.setIoTime(dateTrans);
        tIoWarehouse2.setCompanyId("2");
        ioWarehouseService.save(tIoWarehouse2);

        for (int i = 0; i < myProducts.size(); i++) {

            if (itWareService.selectStatus(myProducts.get(i).getCargoNo()).equals("有货") &&
                    itWareService.selectStatus(myProducts2.get(i).getCargoNo()).equals("无货")
            ) {
                TCargo one = itCargoService.getOneCargo(myProducts.get(i).getCargoNo());
                one.setStatus("无货");
                String product = one.getProduct();
                String productNo = one.getProductNo();
                String iomNo = one.getIomNo();
                String lCode = one.getLCode();
                one.setProduct("1");
                one.setProductNo("1");
                one.setIomNo("1");
                one.setLCode("1");
                TCargo two = itCargoService.getOneCargo(myProducts2.get(i).getCargoNo());
                two.setStatus("有货");
                two.setProduct(product);
                two.setProductNo(productNo);
                two.setIomNo(iomNo);
                two.setLCode(lCode);


                {

                    TIomWarehouse t1 = new TIomWarehouse(UUID.randomUUID().toString().substring(0, 11),
                            myProducts.get(i).getPNumber()
                            , myProducts.get(i).getPName()
                            , myProducts.get(i).getWareName()
                            , myProducts.get(i).getGoodName()
                            , myProducts.get(i).getShelvesNo()
                            , myProducts.get(i).getCargoNo()
                            , dateTrans
                            , id);

                    TIomWarehouse t2 = new TIomWarehouse(UUID.randomUUID().toString().substring(0, 11),
                            myProducts2.get(i).getPNumber()
                            , myProducts2.get(i).getPName()
                            , myProducts2.get(i).getWareName()
                            , myProducts2.get(i).getGoodName()
                            , myProducts2.get(i).getShelvesNo()
                            , myProducts2.get(i).getCargoNo()
                            , dateTrans
                            , id2);
                    iomWarehouseService.save(t1);
                    iomWarehouseService.save(t2);


                }

                itCargoService.updateById(one);
                itCargoService.updateById(two);

            }

        }

        TMoveWarehouse tMoveWarehouse = new TMoveWarehouse(
                UUID.randomUUID().toString().substring(0, 15),
                id,
                myProducts.get(0).getWareName(),
                myProducts2.get(0).getWareName(),
                myProducts.get(0).getPName(),
                Integer.valueOf(mvNumber),
                (String) adm.get("mvMark"),
                (String) adm.get("mvPerson"),
                (String) adm.get("mvTel"),
                dateTrans,
                "2"
        );
        itMoveWarehouseService.save(tMoveWarehouse);


        return new JsonResult(1, "ok", null);
    }

    @PostMapping("/MyInWare")
    public JsonResult MyInWare(@RequestBody Object inmove) throws ParseException {

        System.out.println(inmove);
        LinkedHashMap in = (LinkedHashMap) inmove;
        LinkedHashMap proDetails = (LinkedHashMap) in.get("proDetails");

        LinkedHashMap type = (LinkedHashMap) in.get("type");
        LinkedHashMap goodNameAlls = (LinkedHashMap) in.get("goodNameAlls");
        String ioid = UUID.randomUUID().toString().substring(0, 10);
        String iono = UUID.randomUUID().toString().substring(0, 10);
        String batch = (String) type.get("batch");
        String ioTime = (String) type.get("ioTime");
        String goodName = (String) proDetails.get("goodName");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
        Date dateTrans = format.parse(ioTime);
        TCargo tc = itCargoService.getOneCargo((String) goodNameAlls.get("cargoNo"));
        System.out.println(tc.getStatus().equals("无货"));
        if (tc.getStatus().equals("无货")) {
            TIoWarehouse tIoWarehouse = new TIoWarehouse();
            tIoWarehouse.setId(ioid);
            tIoWarehouse.setIoNo(iono);
            tIoWarehouse.setIoType((String) type.get("ioType"));
            tIoWarehouse.setBatch(Integer.valueOf(batch));
            tIoWarehouse.setPName((String) proDetails.get("pname"));
            tIoWarehouse.setPBrand((String) proDetails.get("pnumber"));
            tIoWarehouse.setPNum(Integer.valueOf(goodName));
            tIoWarehouse.setWName((String) goodNameAlls.get("wareName"));
            tIoWarehouse.setIoTime(dateTrans);
            tIoWarehouse.setCompanyId("2");
            ioWarehouseService.save(tIoWarehouse);

            tc.setStatus("有货");
            tc.setProductNo((String) proDetails.get("pnumber"));
            tc.setProduct((String) proDetails.get("pname"));
            tc.setCreatTime(dateTrans);
            tc.setBatch(Integer.valueOf(batch));
            tc.setIomNo(iono);
            itCargoService.updateById(tc);

            return new JsonResult(1, "ok", null);
        }

        return  new JsonResult(0, "ok", null);


    }


    @RequestMapping("/selectWare/{mvNo}")
    public JsonResult SelectMove(@PathVariable String mvNo ){

        List<String> mvno =  itMoveWarehouseService.selectMvNo(mvNo);
        List<TIomWarehouse> ware1= itMoveWarehouseService.selectAllMove(mvno.get(0));
        List<TIomWarehouse> ware2= itMoveWarehouseService.selectAllMove(mvno.get(1));
        TMoveWarehouse tMove= itMoveWarehouseService.getPerson(mvNo);

        ArrayList<Object> list = new ArrayList<>();
        list.add(ware1);
        list.add(ware2);
        list.add(tMove);

        System.out.println(list);

        return new JsonResult(1,"ok",list);
    }


    @RequestMapping("/inWareType/{inNo}/{type}")
    public JsonResult SelectInWare(@PathVariable String inNo,@PathVariable String type){
        System.out.println(inNo+"++++++++++++++++++++++++++++++++++++++++");
        System.out.println(type.equals("采购订单入库"));
        List<MyProduct> myProduct=null;
        if (type.equals("采购订单入库")){

             myProduct=itWareService.selectinWareNo(inNo);


        }else {
             myProduct= itWareService.selectinWareNo2(inNo);

        }
        System.out.println(myProduct);
        return new JsonResult(1,"ok",myProduct);
    }
}

